package com.aikon.wht.designPattern.async;

import java.util.concurrent.Callable;

/**
 * @author haitao.wang
 */
public class DefaultAsyncExecutor implements AsyncExecutor {
    @Override
    public <T> AsyncResult<T> process(Callable<T> callable) {
        AsyncResult<T> asyncResult = new DefaultAsyncResult();

        new Thread(() -> {
            try {
                asyncResult.setVal(callable.call());
            } catch (Exception e) {
                asyncResult.setException(e);
            }
            System.out.println("TTT");
        }).start();
        System.out.println("YYY");
        return asyncResult;
    }

    @Override
    public <T> AsyncResult<T> process(Callable<T> callable, AsyncCallback<T> asyncCallback) {
        return null;
    }


    @Override
    public <T> T endProcess(AsyncResult<T> asyncResult) throws InterruptedException {
        if (!asyncResult.isCompleted()) {
            asyncResult.await();
        }
        return (T) asyncResult.getVal();
    }
}
